import {
  requestToken
} from './token'

import {
  getToken,
  setToken,
  removeToken,
  removeUserName
} from './auth'

/**
 *  判断是否登录
 *
 * @export
 * @returns {boolean}
 */
export function isLogin() {
  if (getToken()) {
    return true
  } else {
    return false
  }
}

/**
 * 登录逻辑
 *
 * @export
 * @returns {Promise < string >}
 */
export function login() {
  return new Promise((resolve, reject) => {
    // 20190810
    const token = getToken()
    if (token) {
      resolve(token)
    } else {
      const code = getQueryString('code')
      if (code) {
        getRealToken(code).then(
          newtoken => {
            resolve(newtoken)
          },
          err => {
            reject(err)
          }
        );
      } else {
        // 获取授权码
        window.location.href = window.env.loginUrl + '?client_id=' + window.env.clientId + '&response_type=code&redirect_uri=' + delQueryString(window.location.href, 'code')
      }
    }
  })
}
/**
 * 获取token
 *
 * @export
 * @returns {Promise < string >}
 */
export function getRealToken(code) {
  return new Promise((resolve, reject) => {
    requestToken(window.env.clientId, window.env.clientSecret, code)
      .then(
        ResponseSuccess => {
          // 设置token
          setToken(ResponseSuccess.token_type + ResponseSuccess.access_token)
          // 返回token
          resolve(
            ResponseSuccess.token_type + ResponseSuccess.access_token
          )
        },
        ResponseError => {
          reject(ResponseError)
        }
      )
      .catch(() => { })
  })
}

/**
 * 登出
 *
 * @export
 * @param {string} redirectUri
 */
export function logout(redirectUri) {
  // 删除cookie
  removeUserName()
  // 删除token
  removeToken()
  // 20190810
  // FIXME: 删除url中的code 这里会删除url中所有key为code的参数
  const url = delQueryString(redirectUri, 'code');
  window.location.href = window.env.logoutUrl + '?redirect_uri=' + url + '&token=' + getToken()
}

/**
 * 获取url中的参数值
 * @param name 参数名称
 */
export function getQueryString(name) {
  const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  const r = window.location.search.substr(1).match(reg);
  if (r != null) {
    return unescape(r[2]);
  }
  return null;
}

/**
 * 删除url中的指定参数并返回新url
 * @param url 需要截取的url
 * @param ref 需要删除的参数名称
 */
export function delQueryString(url, ref) {
  let str = "";
  if (url.indexOf('?') !== -1) {
    str = url.substr(url.indexOf('?') + 1);
  } else {
    return url;
  }
  let arr = [];
  let returnurl = "";
  if (str.indexOf('&') !== -1) {
    arr = str.split('&');
    let index;
    for (index in arr) {
      if (arr[index].split('=')[0] !== ref) {
        returnurl = returnurl + arr[index].split('=')[0] + "=" + arr[index].split('=')[1] + "&";
      }
    }
    return url.substr(0, url.indexOf('?')) + "?" + returnurl.substr(0, returnurl.length - 1);
  } else {
    arr = str.split('=');
    if (arr[0] === ref) {
      return url.substr(0, url.indexOf('?'));
    } else {
      return url;
    }
  }
}
